<template>
    <div class="sales-report">
        <el-card>
            <!-- 搜索区域 -->
            <div class="search-area">
                <el-form :inline="true" :model="searchForm">
                    <el-form-item label="日期范围">
                        <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                            start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="店铺">
                        <el-select v-model="searchForm.customerId" placeholder="请选择店铺" clearable style="width: 120px">
                            <el-option v-for="item in customerList" :key="item.id" :label="item.shopName" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="销售类型">
                        <el-select v-model="searchForm.salesType" placeholder="请选择销售类型" clearable style="width: 120px">
                            <el-option label="线上" value="ONLINE" />
                            <el-option label="线下" value="OFFLINE" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">查询</el-button>
                        <el-button @click="resetSearch">重置</el-button>
                        <el-button type="success" @click="handleExport">导出</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 统计卡片 -->
            <div class="stat-cards">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-card shadow="hover" class="stat-card">
                            <template #header>
                                <div class="stat-header">总销售额</div>
                            </template>
                            <div class="stat-value">
                                ¥{{ formatAmount(statistics.totalAmount) }}
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover" class="stat-card">
                            <template #header>
                                <div class="stat-header">订单总数</div>
                            </template>
                            <div class="stat-value">{{ statistics.orderCount }}</div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover" class="stat-card">
                            <template #header>
                                <div class="stat-header">总利润</div>
                            </template>
                            <div class="stat-value">
                                ¥{{ formatAmount(statistics.totalProfit) }}
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover" class="stat-card">
                            <template #header>
                                <div class="stat-header">平均利润</div>
                            </template>
                            <div class="stat-value">
                                ¥{{ formatAmount(statistics.averageProfit) }}
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- 图表区域 -->
            <div class="chart-area">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-card class="chart-card">
                            <template #header>
                                <div class="chart-title">销售趋势</div>
                            </template>
                            <div class="chart-container" ref="trendChartContainer"></div>
                        </el-card>
                    </el-col>
                    <el-col :span="12">
                        <el-card class="chart-card">
                            <template #header>
                                <div class="chart-title">销售类型分布</div>
                            </template>
                            <div class="chart-container" ref="statusChartContainer"></div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- 明细表格 -->
            <el-table v-loading="loading" :data="tableData" border style="width: 100%">
                <el-table-column prop="orderNo" label="销售单号" width="180" />
                <el-table-column label="销售日期" width="180">
                    <template #default="scope">
                        {{ formatDateTime(scope.row.salesOrderDate) }}
                    </template>
                </el-table-column>
                <el-table-column prop="operator" label="经办人" width="120" />
                <el-table-column label="销售类型" width="120">
                    <template #default="scope">
                        <el-tag :type="getSalesTypeTag(scope.row.salesType)">
                            {{ getSalesTypeLabel(scope.row.salesType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="销售总额" width="150" align="right">
                    <template #default="scope">
                        ¥{{ formatAmount(scope.row.totalAmount) }}
                    </template>
                </el-table-column>
                <el-table-column label="利润" width="150" align="right">
                    <template #default="scope">
                        ¥{{ formatAmount(getTotalProfit(scope.row.items)) }}
                    </template>
                </el-table-column>
                <el-table-column label="数量" width="100" align="right">
                    <template #default="scope">
                        {{ getTotalQuantity(scope.row.items) }}
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" min-width="150" />
            </el-table>

            <!-- 分页 -->
            <div class="pagination">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import * as echarts from 'echarts'
import { salesOrderApi } from '../../api'
import { fetchShopList } from '../../utils/commonMethods';
// 搜索表单
const searchForm = reactive({
    dateRange: [],
    customerId: '',
    salesType: ''
})

// 店铺列表
const customerList = ref([])
// 获取店铺列表
const getCustomerList = async () => {
    customerList.value = await fetchShopList();
};
// 统计数据
const statistics = reactive({
    totalAmount: 0,      // 总销售额
    orderCount: 0,       // 订单总数
    totalProfit: 0,      // 总利润
    averageProfit: 0     // 平均利润
})

// 表格数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 图表实例
let trendChart = null
let statusChart = null

// 添加一个存储所有数据的变量
const allData = ref([])

// 计算当前页数据
const tableData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return allData.value.slice(start, end)
})
// 获取报表数据
const getReportData = async () => {
    loading.value = true
    try {
        const params = {
            startDate: searchForm.dateRange?.[0],
            endDate: searchForm.dateRange?.[1],
            customerId: searchForm.customerId || undefined,
            salesType: searchForm.salesType || undefined,
        }

        const { data } = await salesOrderApi.getListAll(params)
        // 获取并排序日期数组
        const sortedDates = data.sort((a, b) => new Date(a.salesOrderDate) - new Date(b.salesOrderDate))
        // 更新表格数据
        allData.value = sortedDates
        total.value = sortedDates.length
        if (data.length <= 0) {
            resetCharts()
            return
        }

        // 计算统计数据
        calculateStatistics(sortedDates)

        // 更新图表
        updateChartsData(sortedDates)



    } catch (error) {
        console.error('获取数据失败:', error)
        ElMessage.error(error.message || '获取数据失败')
    } finally {
        loading.value = false
    }
}

// 计算统计数据
const calculateStatistics = (records) => {
    if (!records || !records.length) {
        Object.assign(statistics, {
            totalAmount: 0,
            orderCount: 0,
            totalProfit: 0,
            averageProfit: 0
        })
        return
    }

    // 计算总销售额
    const totalAmount = records.reduce((sum, record) =>
        sum + Number(record.totalAmount || 0), 0)

    // 计算总利润
    const totalProfit = records.reduce((sum, record) =>
        sum + record.items.reduce((itemSum, item) =>
            itemSum + Number(item.profit || 0), 0), 0)

    // 订单数量
    const orderCount = records.length

    // 计算平均利润
    const averageProfit = orderCount > 0 ? totalProfit / orderCount : 0

    // 更新统计数据
    Object.assign(statistics, {
        totalAmount,
        orderCount,
        totalProfit,
        averageProfit
    })
}
// 重置图表
const resetCharts = () => {
    if (trendChart && statusChart) {
        // 重置销售趋势图（包含销售额和利润两个系列）
        trendChart.setOption({
            series: [
                {
                    name: '销售额',
                    data: []
                },
                {
                    name: '利润',
                    data: []
                }
            ]
        })

        // 重置销售类型分布图
        statusChart.setOption({
            series: [{
                type: 'pie',
                data: []
            }]
        })
    }
}
// 更新图表数据
const updateChartsData = (records) => {
    if (!records || !records.length) return

    // 按日期分组数据
    const dateGroups = {}
    records.forEach(record => {
        const date = record.salesOrderDate.split(' ')[0]
        if (!dateGroups[date]) {
            dateGroups[date] = {
                amount: 0,
                profit: 0
            }
        }
        dateGroups[date].amount += Number(record.totalAmount || 0)
        dateGroups[date].profit += record.items.reduce((sum, item) => sum + Number(item.profit || 0), 0)
    })

    // 按销售类型分组数据
    const typeGroups = {}
    records.forEach(record => {
        if (!typeGroups[record.salesType]) {
            typeGroups[record.salesType] = 0
        }
        typeGroups[record.salesType] += Number(record.totalAmount || 0)
    })

    // 更新图表
    updateCharts({
        trend: {
            dates: Object.keys(dateGroups),
            amounts: Object.values(dateGroups).map(g => g.amount),
            profits: Object.values(dateGroups).map(g => g.profit)
        },
        salesTypes: Object.entries(typeGroups).map(([type, amount]) => ({
            type: getSalesTypeLabel(type),
            amount
        }))
    })
}

// 更新图表
const updateCharts = (chartData) => {
    if (!trendChart || !statusChart) return

    // 销售趋势图
    trendChart.setOption({
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['销售额', '利润']
        },
        xAxis: {
            type: 'category',
            data: chartData.trend.dates
        },
        yAxis: {
            type: 'value',
            name: '金额',
            axisLabel: {
                formatter: (value) => `¥${formatAmount(value)}`
            }
        },
        series: [
            {
                name: '销售额',
                data: chartData.trend.amounts,
                type: 'bar'
            },
            {
                name: '利润',
                data: chartData.trend.profits,
                type: 'line',
                smooth: true
            }
        ]
    })

    // 销售类型分布图
    statusChart.setOption({
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left'
        },
        series: [{
            type: 'pie',
            radius: '50%',
            data: chartData.salesTypes.map(item => ({
                name: item.type,
                value: item.amount
            })),
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }]
    })
}

// 初始化图表
const initCharts = () => {
    const trendChartContainer = document.querySelector('.chart-container')
    const statusChartContainer = document.querySelectorAll('.chart-container')[1]

    if (trendChartContainer && statusChartContainer) {
        trendChart?.dispose()
        statusChart?.dispose()

        trendChart = echarts.init(trendChartContainer)
        statusChart = echarts.init(statusChartContainer)

        getReportData()
    }
}

// 监听窗口大小变化
const handleResize = () => {
    trendChart?.resize()
    statusChart?.resize()
}

// 格式化金额
const formatAmount = (amount) => {
    if (amount === undefined || amount === null || isNaN(amount)) {
        return '0.00'
    }
    return Number(amount).toFixed(2)
}

// 格式化日期时间
const formatDateTime = (datetime) => {
    if (!datetime) return '---'
    return new Date(datetime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    })
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    getReportData()
}

// 重置搜索
const resetSearch = () => {
    searchForm.dateRange = []
    searchForm.salesType = ''
    handleSearch()
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
}

const handleCurrentChange = (val) => {
    currentPage.value = val
}

// 导出数据
const handleExport = async () => {
    try {
        const params = {
            startDate: searchForm.dateRange?.[0],
            endDate: searchForm.dateRange?.[1],
            orderNo: searchForm.orderNo || undefined,
            customerName: searchForm.customerName || undefined,
            salesType: searchForm.salesType || undefined
        }

        await orderApi.exportReport(params)
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败')
    }
}

// 获取订单总利润
const getTotalProfit = (items) => {
    if (!items || !items.length) return 0
    return items.reduce((sum, item) => sum + (item.profit || 0), 0)
}

// 获取订单总数量
const getTotalQuantity = (items) => {
    if (!items || !items.length) return 0
    return items.reduce((sum, item) => sum + (item.quantity || 0), 0)
}

// 销售类型标签
const getSalesTypeTag = (type) => {
    const types = {
        'ONLINE': 'success',
        'OFFLINE': 'primary'
    }
    return types[type] || 'info'
}

// 销售类型显示文本
const getSalesTypeLabel = (type) => {
    const labels = {
        'ONLINE': '线上',
        'OFFLINE': '线下'
    }
    return labels[type] || type
}

// 组件挂载时
onMounted(() => {
    initCharts()
    getCustomerList()
    window.addEventListener('resize', handleResize)
})

// 组件卸载时
onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    trendChart?.dispose()
    statusChart?.dispose()
})
</script>

<style lang="scss" scoped>
.sales-report {
    height: 100%;
    background-color: #f5f7fa;
    padding: 20px;
    box-sizing: border-box;
    overflow: hidden;
    min-width: 1200px;
}

.el-card {
    height: 100%;
    overflow-y: auto;
}

.search-area {
    margin-bottom: 20px;
}

.stat-cards {
    margin-bottom: 20px;
}

.stat-card {
    text-align: center;
}

.stat-header {
    font-size: 14px;
    color: #606266;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin-top: 10px;

    // 添加数字过长时的处理
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.chart-area {
    margin-bottom: 20px;
}

.chart-card {
    margin-bottom: 20px;
}

.chart-title {
    font-size: 16px;
    font-weight: bold;
}

.chart-container {
    height: 300px;
    width: 100%;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

// 为利润相关的统计添加特殊样式
.stat-card:nth-child(3) .stat-value,
.stat-card:nth-child(4) .stat-value {
    color: #67C23A; // 使用绿色显示利润
}
</style>